import { ref, computed, reactive, unref, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { apiInit } from '../../../../services'
import { client, path } from '../../../../utils'
import { t } from '@/constant/welcome'
import axios from 'axios'
export function useWelcome(message: any) {
	const pcFlag = ref()
	const isDisabled = ref(false)
	const codeValue = ref('')
	const phoneNumber = ref('')
	const requestDisabled = ref(false)
	const restTime = ref('59s')
	const warning = ref(false)
	const alertText = ref('')
	const alertWidth = ref('')
	const alertType = ref('')
	// 图形验证码的显示隐藏
	const isShow = ref(false)
	const create_source = ref()
	const pas_status = ref()
	const puc_status = ref()
	// 注册用户详情
	const invitee = ref('')

	const store = useStore()
	const router = useRouter()
	const api = apiInit()

	const language = computed(
		() =>
			store.state.tenant?.language_list?.filter((item: any) => item.has_show) ??
			[]
	)

	const currentValue = reactive({
		name: '中文',
		value: 'zh-CN',
	})
	const isShowLang = ref(false)

	const imgs = [
		'/images/rjcodepic/p1.jpg',
		'/images/rjcodepic/p2.jpg',
		'/images/rjcodepic/p3.jpg',
		'/images/rjcodepic/p4.jpg',
		'/images/rjcodepic/p5.jpg',
		'/images/rjcodepic/p6.jpg',
		'/images/rjcodepic/p7.jpg',
		'/images/rjcodepic/p8.jpg',
		'/images/rjcodepic/p9.jpg',
		'/images/rjcodepic/p10.jpg',
	]
	const changeLocale = async (lang: any) => {
		currentValue.name = lang.name
		currentValue.value = lang.value
		isShowLang.value = false

		await api.default.SetLocalLanguagePrivateV2POST({
			query: {
				localLanguage: lang.value,
			},
		})
		localStorage.setItem('locale', lang.value)
		location.reload()
	}

	// // 提示框
	// const alertTip = (state: string, text: string, width: string): void => {
	// 	alertType.value = state
	// 	alertText.value = text
	// 	alertWidth.value = width
	// 	warning.value = true
	// 	observeAlertTime(3000)
	// }

	// 获取验证码
	const getCode = async () => {
		isShow.value = false

		const isPhoneNum = phoneNumber.value.match(
			/^((\+|00)86)?1((3[\d])|(4[5,6,7,9])|(5[0-3,5-9])|(6[5-7])|(7[0-8])|(8[\d])|(9[1,8,9]))\d{8}$/
		)
		if (!!isPhoneNum) {
			//是否来自ptm租户
			const res = await axios({
				method: 'POST',
				url: `/ego_base_info/api/public/tenant/getPlatformInfo`,
			})

			if (res.data.code === '000000') {
				create_source.value = res.data.data.create_source
				pas_status.value = res.data.data.pas_status
				puc_status.value = res.data.data.puc_status
			}
			let result: any = {}
			if (
				create_source.value === 'PTM' &&
				pas_status.value &&
				puc_status.value
			) {
				const data = await axios({
					method: 'GET',
					url: `${res.data.data.puc_domain}/user_center/api/public/verify-code/sms`,
					params: {
						biz_type: 'BIND_PHONE',
						phone: phoneNumber.value,
					},
				})
				result = data.data || { code: 'xx', msg: '短信发送出错' }
			} else {
				result = await api.userCenterAuto.SmsVerifyCodePublicApiGET({
					query: {
						bizType: 'BIND_PHONE',
						phone: phoneNumber.value,
					},
				})
			}
			if (result && result.code === '000000') {
				message.success(t.hasSendCode)
				requestDisabled.value = true
				const beginTime: any = new Date().getTime()
				observeTime(beginTime)
			} else {
				message.error(result.msg as string)
			}
		} else {
			message.error(t.checkPhone)
		}
	}

	// 监听请求验证码的剩余时间
	const observeTime = (beginTime: any) => {
		const timer = setInterval(() => {
			const curTime = new Date().getTime()
			restTime.value = `${Math.round(59 - (curTime - beginTime) / 1000)}s`
			if (parseInt(restTime.value) < 0) {
				requestDisabled.value = false
				restTime.value = '59s'
				localStorage.removeItem('bindBeginTime')
				clearInterval(timer)
			}
		}, 1000)
	}

	// 监听提示框存在的时间
	// const observeAlertTime = (delay: number) => {
	// 	let alertTimer: any = setTimeout(() => {
	// 		warning.value = false
	// 		alertTimer = null
	// 	}, delay)
	// }
	const type = {
		DINGDING: 'DINGDING',
		LARK: 'FEISHU',
	}
	// 登录
	const login = async () => {
		const result = await api.default.BindPhoneUserCenterPrivateV1POST({
			payload: {
				biz_integration_type: '',
				code: codeValue.value,
				phone: phoneNumber.value,
				tenant_id: store.state.tenant.tenant_id,
				tenant_type: store.state.tenant.is_private_environment ? 'PRI' : 'SAAS',
				tenant_user_id: store.state.userInfo.employee_id,
				union_id: store.state.userInfo.union_id,
			},
		})
		if (result.code === '000000') {
			window.location.href = path.getFullPath(
				pcFlag.value ? '/' : '/ego/mobile/myTask'
			)
		} else {
			message.error(result.message)
		}
	}

	onMounted(() => {
		pcFlag.value = client.isPc()
		invitee.value = store.state.userInfo.employee_name
		phoneNumber.value = store.state.userInfo.phone
		// 语言设置
		if (localStorage.getItem('locale')) {
			currentValue.value = localStorage.getItem('locale') || 'zh-CN'
			const currentName = unref(language)?.filter((item: any) => {
				return item.value === currentValue.value
			})
			currentValue.name = currentName[0].name
		} else {
			localStorage.setItem('locale', currentValue.value)
		}
	})

	// 点击获取验证码按钮，弹出图形验证码
	const onOpen = () => {
		isShow.value = true
	}
	//  点击图形验证码弹窗的遮罩，隐藏图形验证码
	const onClose = () => {
		isShow.value = false
	}

	// 监听是否输入验证码，动态修改按钮禁用的样式
	watch(
		[() => codeValue.value, () => phoneNumber.value],
		curVal => {
			isDisabled.value = curVal.some(item => {
				return !item
			})
		},
		{
			deep: true,
			immediate: true,
		}
	)
	return {
		currentValue,
		language,
		changeLocale,
		isDisabled,
		codeValue,
		requestDisabled,
		restTime,
		warning,
		alertText,
		alertWidth,
		alertType,
		getCode,
		login,
		phoneNumber,
		invitee,
		isShow,
		onOpen,
		onClose,
		imgs,
	}
}
